package main

import (
	"context"
	"fmt"
	greeter "go_final/demos/grpc_metadata/protofile"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
)

func main() {
	interceptor := grpc.UnaryClientInterceptor(func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()

		// 注入鉴权信息
		md1 := metadata.New(map[string]string{
			"appid":  "101010",
			"appkey": "I am key",
		})

		ctx = metadata.NewOutgoingContext(ctx, md1)

		err := invoker(ctx, method, req, reply, cc)
		fmt.Println("耗时: %s", time.Since(start))
		return err
	})
	opt := grpc.WithUnaryInterceptor(interceptor)
	conn, err := grpc.Dial(":8080", grpc.WithInsecure(), opt)
	if err != nil {
		panic(err)
	}
	defer conn.Close()

	c := greeter.NewGreeterClient(conn)

	res, err := c.SayHi(context.Background(), &greeter.SayHiRequest{
		Id: "Felix",
	})
	if err != nil {
		fmt.Println("err", err)
	}
	fmt.Println("res", res)
}
